/*
 * To change this template, choose Tools | Templates
 * and open the template in the editor.
 */
package View;

import Controller.RendererArbol;
import Controller.TreeDragSource;
import Controller.TreeDropTarget;
import ControllerInterface.IControllerSchemaMapping;
import ViewInterface.IViewSchema;
import java.awt.dnd.DnDConstants;
import java.awt.event.ActionEvent;
import java.awt.event.KeyEvent;
import javax.swing.*;
import javax.swing.text.Position;
import javax.swing.tree.DefaultMutableTreeNode;
import javax.swing.tree.DefaultTreeModel;
import javax.swing.tree.MutableTreeNode;
import javax.swing.tree.TreePath;

/**
 *
 * @author Fabian
 */
public class ViewSchema extends javax.swing.JFrame implements IViewSchema {

    private IControllerSchemaMapping myController;
    private DefaultTreeModel modelTreeS;
    private DefaultTreeModel modelTreeT;
    TreeDragSource ds;
    TreeDropTarget dt;

    /**
     * 
     */
    public ViewSchema() {
        initComponents();
        keyMapping();
    }

    /**
     * This method is called from within the constructor to initialize the form.
     * WARNING: Do NOT modify this code. The content of this method is always
     * regenerated by the Form Editor.
     */
    @SuppressWarnings("unchecked")
    // <editor-fold defaultstate="collapsed" desc="Generated Code">//GEN-BEGIN:initComponents
    private void initComponents() {

        jScrollPane1 = new javax.swing.JScrollPane();
        jTreeSource = new javax.swing.JTree();
        jScrollPane2 = new javax.swing.JScrollPane();
        jTreeTarget = new javax.swing.JTree();
        jLabel1 = new javax.swing.JLabel();
        jLabel2 = new javax.swing.JLabel();
        jbtnMapear = new javax.swing.JButton();
        jtxtNameTypeEvent = new javax.swing.JTextField();
        jLabel3 = new javax.swing.JLabel();
        jLabel4 = new javax.swing.JLabel();
        jbtnAgregarTipoEvento = new javax.swing.JButton();

        setDefaultCloseOperation(javax.swing.WindowConstants.DISPOSE_ON_CLOSE);

        jScrollPane1.setViewportView(jTreeSource);

        jTreeTarget.setAutoscrolls(true);
        jTreeTarget.setDebugGraphicsOptions(javax.swing.DebugGraphics.NONE_OPTION);
        jScrollPane2.setViewportView(jTreeTarget);

        jLabel1.setText("Mapeo de datos");

        jLabel2.setText("Para realizar la asignación, seleccione y arrastre lo datos desde el dataset \"Fuente\" hacia el dataset \"Destino\".");

        jbtnMapear.setText("Iniciar Mapeo de datos");
        jbtnMapear.addActionListener(new java.awt.event.ActionListener() {
            public void actionPerformed(java.awt.event.ActionEvent evt) {
                jbtnMapearActionPerformed(evt);
            }
        });

        jtxtNameTypeEvent.setHorizontalAlignment(javax.swing.JTextField.LEFT);
        jtxtNameTypeEvent.addActionListener(new java.awt.event.ActionListener() {
            public void actionPerformed(java.awt.event.ActionEvent evt) {
                jtxtNameTypeEventActionPerformed(evt);
            }
        });

        jLabel3.setText("Crear tipo de evento");

        jLabel4.setText("Nombre del tipo ");

        jbtnAgregarTipoEvento.setText("Agregar tipo de evento");
        jbtnAgregarTipoEvento.addActionListener(new java.awt.event.ActionListener() {
            public void actionPerformed(java.awt.event.ActionEvent evt) {
                jbtnAgregarTipoEventoActionPerformed(evt);
            }
        });

        javax.swing.GroupLayout layout = new javax.swing.GroupLayout(getContentPane());
        getContentPane().setLayout(layout);
        layout.setHorizontalGroup(
            layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
            .addGroup(layout.createSequentialGroup()
                .addContainerGap()
                .addGroup(layout.createParallelGroup(javax.swing.GroupLayout.Alignment.TRAILING)
                    .addGroup(layout.createSequentialGroup()
                        .addGroup(layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
                            .addComponent(jLabel2)
                            .addComponent(jLabel1))
                        .addGap(0, 0, Short.MAX_VALUE))
                    .addGroup(layout.createSequentialGroup()
                        .addComponent(jScrollPane1, javax.swing.GroupLayout.PREFERRED_SIZE, 270, javax.swing.GroupLayout.PREFERRED_SIZE)
                        .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED, 11, Short.MAX_VALUE)
                        .addGroup(layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
                            .addGroup(javax.swing.GroupLayout.Alignment.TRAILING, layout.createSequentialGroup()
                                .addComponent(jLabel3)
                                .addGap(99, 99, 99))
                            .addGroup(javax.swing.GroupLayout.Alignment.TRAILING, layout.createSequentialGroup()
                                .addComponent(jbtnAgregarTipoEvento)
                                .addContainerGap())
                            .addGroup(javax.swing.GroupLayout.Alignment.TRAILING, layout.createSequentialGroup()
                                .addGroup(layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
                                    .addGroup(javax.swing.GroupLayout.Alignment.TRAILING, layout.createSequentialGroup()
                                        .addComponent(jLabel4)
                                        .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.UNRELATED)
                                        .addComponent(jtxtNameTypeEvent, javax.swing.GroupLayout.PREFERRED_SIZE, 145, javax.swing.GroupLayout.PREFERRED_SIZE))
                                    .addComponent(jScrollPane2, javax.swing.GroupLayout.Alignment.TRAILING, javax.swing.GroupLayout.PREFERRED_SIZE, 284, javax.swing.GroupLayout.PREFERRED_SIZE))
                                .addContainerGap())))))
            .addGroup(layout.createSequentialGroup()
                .addGap(210, 210, 210)
                .addComponent(jbtnMapear)
                .addGap(0, 0, Short.MAX_VALUE))
        );
        layout.setVerticalGroup(
            layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
            .addGroup(javax.swing.GroupLayout.Alignment.TRAILING, layout.createSequentialGroup()
                .addContainerGap()
                .addComponent(jLabel1)
                .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.UNRELATED)
                .addComponent(jLabel2)
                .addGap(18, 18, 18)
                .addGroup(layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
                    .addGroup(layout.createSequentialGroup()
                        .addComponent(jScrollPane2, javax.swing.GroupLayout.PREFERRED_SIZE, 0, Short.MAX_VALUE)
                        .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.UNRELATED)
                        .addComponent(jLabel3)
                        .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.UNRELATED)
                        .addGroup(layout.createParallelGroup(javax.swing.GroupLayout.Alignment.BASELINE)
                            .addComponent(jtxtNameTypeEvent, javax.swing.GroupLayout.PREFERRED_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.PREFERRED_SIZE)
                            .addComponent(jLabel4))
                        .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.UNRELATED)
                        .addComponent(jbtnAgregarTipoEvento))
                    .addComponent(jScrollPane1, javax.swing.GroupLayout.DEFAULT_SIZE, 330, Short.MAX_VALUE))
                .addGap(18, 18, 18)
                .addComponent(jbtnMapear)
                .addGap(21, 21, 21))
        );

        jLabel4.getAccessibleContext().setAccessibleName("Nombre del tipo");

        pack();
    }// </editor-fold>//GEN-END:initComponents

    private void jbtnAgregarTipoEventoActionPerformed(java.awt.event.ActionEvent evt) {//GEN-FIRST:event_jbtnAgregarTipoEventoActionPerformed

        String tipoEvento = this.jtxtNameTypeEvent.getText();

        if (tipoEvento.length() < 1) {
            return;
        }
        DefaultTreeModel model = (DefaultTreeModel) this.jTreeTarget.getModel();

        // Find node to which new node is to be added
        int startRow = 0;
        String prefix = "typeevent";
        TreePath path = jTreeTarget.getNextMatch(prefix, startRow,
                Position.Bias.Forward);
        MutableTreeNode node = (MutableTreeNode) path.getLastPathComponent();
        // Create new node
        MutableTreeNode newNode = new DefaultMutableTreeNode(tipoEvento);
        // Insert new node as last child of node
        model.insertNodeInto(newNode, node, node.getChildCount());
        this.jtxtNameTypeEvent.setText("");
        this.jTreeTarget.setModel(model);
    }//GEN-LAST:event_jbtnAgregarTipoEventoActionPerformed

    private void jbtnMapearActionPerformed(java.awt.event.ActionEvent evt) {//GEN-FIRST:event_jbtnMapearActionPerformed
        int i = JOptionPane.showConfirmDialog(this,
                "Comenzará el proceso de mapeo de datos ¿Desea continuar?",
                "Confirmar Mapeo de datos",
                JOptionPane.YES_NO_OPTION);
        if (i == 0) {
            this.modelTreeT = (DefaultTreeModel) this.jTreeTarget.getModel();
            boolean ok = this.myController.setTargetModelMap(modelTreeT);
            this.enable(false);
        }
    }//GEN-LAST:event_jbtnMapearActionPerformed

    private void jtxtNameTypeEventActionPerformed(java.awt.event.ActionEvent evt) {//GEN-FIRST:event_jtxtNameTypeEventActionPerformed
        // TODO add your handling code here:
    }//GEN-LAST:event_jtxtNameTypeEventActionPerformed

    /**
     * @param args the command line arguments
     */
    public static void main(String args[]) {
        /*
         * Set the Nimbus look and feel
         */
        //<editor-fold defaultstate="collapsed" desc=" Look and feel setting code (optional) ">
        /*
         * If Nimbus (introduced in Java SE 6) is not available, stay with the
         * default look and feel. For details see
         * http://download.oracle.com/javase/tutorial/uiswing/lookandfeel/plaf.html
         */
        try {
            for (javax.swing.UIManager.LookAndFeelInfo info : javax.swing.UIManager.getInstalledLookAndFeels()) {
                if ("Nimbus".equals(info.getName())) {
                    javax.swing.UIManager.setLookAndFeel(info.getClassName());
                    break;
                }
            }
        } catch (ClassNotFoundException ex) {
            java.util.logging.Logger.getLogger(ViewSchema.class.getName()).log(java.util.logging.Level.SEVERE, null, ex);
        } catch (InstantiationException ex) {
            java.util.logging.Logger.getLogger(ViewSchema.class.getName()).log(java.util.logging.Level.SEVERE, null, ex);
        } catch (IllegalAccessException ex) {
            java.util.logging.Logger.getLogger(ViewSchema.class.getName()).log(java.util.logging.Level.SEVERE, null, ex);
        } catch (javax.swing.UnsupportedLookAndFeelException ex) {
            java.util.logging.Logger.getLogger(ViewSchema.class.getName()).log(java.util.logging.Level.SEVERE, null, ex);
        }
        //</editor-fold>

        /*
         * Create and display the form
         */
        java.awt.EventQueue.invokeLater(new Runnable() {

            public void run() {
                new ViewSchema().setVisible(true);
            }
        });
    }
    // Variables declaration - do not modify//GEN-BEGIN:variables
    private javax.swing.JLabel jLabel1;
    private javax.swing.JLabel jLabel2;
    private javax.swing.JLabel jLabel3;
    private javax.swing.JLabel jLabel4;
    private javax.swing.JScrollPane jScrollPane1;
    private javax.swing.JScrollPane jScrollPane2;
    private javax.swing.JTree jTreeSource;
    private javax.swing.JTree jTreeTarget;
    private javax.swing.JButton jbtnAgregarTipoEvento;
    private javax.swing.JButton jbtnMapear;
    private javax.swing.JTextField jtxtNameTypeEvent;
    // End of variables declaration//GEN-END:variables

    /*
     * Metodo que se encarga de tomar los eventos del teclado. En este caso solo
     * se usa la tecla DEL
     */
    /**
     * 
     */
    public void keyMapping() {
        ActionMap mapaAccion = this.jTreeTarget.getActionMap();
        InputMap map = this.jTreeTarget.getInputMap(JComponent.WHEN_ANCESTOR_OF_FOCUSED_COMPONENT);
        KeyStroke key_Del = KeyStroke.getKeyStroke(KeyEvent.VK_DELETE, 0);
        //Key Actions
        map.put(key_Del, "actionDel");
        mapaAccion.put("actionDel", ActionDel());

    }

    private Action ActionDel() {
        return new AbstractAction() {

            public void actionPerformed(ActionEvent e) {
                deleteNode();
            }
        };
    }
    /*
     * Metodo que elimina el nodo seleccionado en el arbol destino
     */

    private void deleteNode() {

        DefaultTreeModel model = (DefaultTreeModel) jTreeTarget.getModel();
        TreePath path = jTreeTarget.getSelectionPath();
        DefaultMutableTreeNode node = (DefaultMutableTreeNode) path.getLastPathComponent();

        // Remove node; if node has descendants, all descendants are removed as well
        //solo elimina las columnas que han sido arrastradas al destino
        if (node.isLeaf() && node.getLevel() > 2) {
            
            model.removeNodeFromParent(node);
        } else {
            if (node.isLeaf() && node.getParent().toString().equals("typeevent")) {
                
                model.removeNodeFromParent(node);
            }
        }
//        System.out.println("Tecla DEL apretada en jtreeTarget");
    }

    /**
     * 
     * @param controllerSchema
     */
    @Override
    public void setController(IControllerSchemaMapping controllerSchema) {
        this.myController = controllerSchema;
    }

    /**
     * 
     * @param modelTreeS
     * @param modelTreeT
     */
    @Override
    public void setModelTree(DefaultTreeModel modelTreeS, DefaultTreeModel modelTreeT) {
        this.modelTreeS = modelTreeS;
        this.modelTreeT = modelTreeT;
        this.jTreeSource.setModel(modelTreeS);
        this.jTreeTarget.setModel(modelTreeT);
        jTreeTarget.setCellRenderer(new RendererArbol());
        jTreeSource.setCellRenderer(new RendererArbol());
        ds = new TreeDragSource(jTreeSource, DnDConstants.ACTION_COPY);
        dt = new TreeDropTarget(jTreeTarget);
    }

    /**
     * 
     * @param b
     */
    @Override
    public void setVisibleViewMain(boolean b) {
        this.setVisible(b);
    }

    /**
     * 
     * @param ok
     */
    @Override
    public void mapFinish(boolean ok) {
        
        if(ok)
        JOptionPane.showMessageDialog(null, "Mapeo de datos realizado exitosamente",
                "Mapeo exitoso!",
                JOptionPane.INFORMATION_MESSAGE); 
        this.enable(true);
    }
}
